package com.oreilly.ez.fileserver.service.impl;


import com.oreilly.ez.fileserver.entity.NoteCate;
import com.oreilly.ez.fileserver.repo.NoteCateRepo;
import com.oreilly.ez.fileserver.service.INoteCateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class NoteCateService implements INoteCateService {

   @Autowired
   private NoteCateRepo noteCateRepo;

    @Override
    public void add(NoteCate noteCate) {
        noteCateRepo.save(noteCate);
    }

    @Override
    public void deleteByIds(String[] ids) {

        for (String id : ids) {
            noteCateRepo.deleteById(id);
        }
    }

    @Override
    public void update(NoteCate NoteCate) {

        noteCateRepo.save(NoteCate);
    }

    @Override
    public Page<NoteCate> find(NoteCate noteCate, Pageable pageable) {
        Specification<NoteCate> specification = (root, query, criteriaBuilder) -> {

            List<Predicate> list = new ArrayList<>();
            String cateCode = noteCate.getCateCode();
            if(StringUtils.isNotBlank(cateCode)){

                list.add(criteriaBuilder.like(root.get("cateCode").as(String.class), "%" + cateCode + "%"));
            }

            String title = noteCate.getTitle();
            if(StringUtils.isNotBlank(title)){
                list.add(criteriaBuilder.like(root.get("title").as(String.class), "%" + cateCode + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        return noteCateRepo.findAll(specification, pageable);
    }

    @Override
    public NoteCate findById(String id) {
        return noteCateRepo.findById(id).get();
    }


}
